package com.eurake.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eurake.seckill.mapper.SeckillOrdersMapper;
import com.eurake.seckill.pojo.SeckillOrders;
import com.eurake.seckill.pojo.User;
import com.eurake.seckill.service.ISeckillOrdersService;
import com.eurake.seckill.vo.RespBean;
import com.eurake.seckill.vo.SeckillOrdersVo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.temporal.Temporal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chen
 * @since 2024-11-24
 */
@Service
public class SeckillOrdersServiceImpl extends ServiceImpl<SeckillOrdersMapper, SeckillOrders> implements ISeckillOrdersService {
    @Resource
    private SeckillOrdersMapper seckillOrdersMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public List<SeckillOrdersVo> findOrderByUserIdAndGoodsId(Long userId, Long goodsId) {
        return seckillOrdersMapper.findOrderByUserIdAndGoodsId(userId,goodsId);
    }

    //存在非0的goodsId即为成功，0为排队中，-1为秒杀失败
    @Override
    public Long getResult(User user, Long goodsId) {
        SeckillOrders seckillOrders = (SeckillOrders) redisTemplate.opsForValue().get("order:"+user.getId()+":"+goodsId);
        if(seckillOrders != null){
            return seckillOrders.getOrderId();
        }else if (redisTemplate.hasKey("isStockEmpty:"+goodsId)){
            //无库存了
            return -1L;
        }
        return 0L;
    }
}
